<template>
  <div>
    <!-- 录入按钮 -->
    <div class="toAdd">
      <!-- 一行两列 -->
      <el-row>
        <el-col :span="20" style="height: 32px"></el-col>
        <el-col :span="4" style="text-align: right">
          <el-button type="primary" @click="toAdd">录入</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="search">
      <!-- {{ form }} -->
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item>
          <el-select clearable v-model="form.online_status" placeholder="请选择工程类型">
            <el-option label="在线" value="1"></el-option>
            <el-option label="离线" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select clearable v-model="form.bind_status" placeholder="请选择工程状态">
            <el-option label="监测中" value="0"></el-option>
            <el-option label="未绑定" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="form.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据 -->
    <div class="table">
      <el-table :data="engData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80px">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180px">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="380px">
        </el-table-column>
        <el-table-column prop="type" label="工程类型">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.status === '监测中'" type="success">监测中</el-tag>
              <el-tag v-else-if="scope.row.status === '未绑定'" type="warning">未绑定</el-tag>
              <el-tag v-else type="danger">已结束</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <div>
              <el-button type="text" @click="toEdit(scope.row)">修改</el-button>
              <el-button type="text" v-if="scope.row.status === '已结束'" disabled>绑定</el-button>
              <el-button type="text" v-if="scope.row.status === '监测中' || scope.row.status === '未绑定'"
                @click="toDetails(scope.row)">绑定</el-button>
              <el-button type="text" v-if="scope.row.status === '监测中'" @click="tofinish(scope.row.id)">结束</el-button>
              <el-button type="text" v-if="scope.row.status === '未绑定' || scope.row.status === '已结束'"
                disabled>结束</el-button>
              <el-button type="text" v-if="scope.row.status === '未绑定'" @click="toDelete(scope.row.id)">删除</el-button>
              <el-button type="text" v-if="scope.row.status === '监测中' || scope.row.status === '已结束'"
                disabled>删除</el-button>
            </div>
          </template>

        </el-table-column>
      </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="page" style="margin-top:15px;text-align:right">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.page"
        :page-sizes="[2, 5, 10, 20]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total" hide-on-single-page>
      </el-pagination>
    </div>
    <!-- 抽屉 -->
    <!-- close抽屉事件 关闭模态框做什么事  -->
    <el-drawer @close="toClose" size="50%" :title="title" :visible.sync="dialog" direction="rtl"
      custom-class="demo-drawer" ref="drawer">
      <div class="demo-drawer__content">
        <el-form ref="myForm" :model="form" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="serial_number" label="编号" :label-width="formLabelWidth">
                <el-input v-model="form.serial_number" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="工程类型" :label-width="formLabelWidth">
                <el-select clearable v-model="form.type" placeholder="请选择工程类型">
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="charge_id" label="区域经理" :label-width="formLabelWidth">
                <el-select clearable v-model="form.charge_id" placeholder="请选择区域经理">
                  <el-option v-for="item in cData" :key="item.id" :label="item.realname" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="longitude" label="经度" :label-width="formLabelWidth">
                <el-input v-model="form.longitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop='latitude' label="纬度" :label-width="formLabelWidth">
                <el-input v-model="form.latitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="address1" label="地址" :label-width="formLabelWidth">
                <el-cascader v-model="form.address1" :props="{
                  value: 'name',
                  label: 'name'
                }" :options="options" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="address2" label="详细地址" :label-width="formLabelWidth">
                <el-input v-model="form.address2" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customer_name" label="客户姓名" :label-width="formLabelWidth">
                <el-input v-model="form.customer_name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customer_telephone" label="客户电话" :label-width="formLabelWidth">
                <el-input v-model="form.customer_telephone" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="dialog = false">取消</el-button>
          <el-button type="primary" @click="toSave">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
// 引入get方法
import { get, postJSON, del } from '@/utils/request'
// 引入省市区数据
import pca from '@/assets/pca.json'
export default {
  // 数据模型 vue变量
  data() {
    return {
      // 区域经理信息
      cData: [],
      // 表单验证规则
      rules: {
        serial_number: [
          { required: true, message: '请输入工程编号', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入工程名称', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择工程类型', trigger: 'change' },
        ],
        charge_id: [
          { required: true, message: '请选择区域经理', trigger: 'change' },
        ],
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' },
        ],
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' },
        ],
        address1: [
          { required: true, message: '请选择地址', trigger: 'change' },
        ],
        address2: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
        ],
        customer_name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' },
        ],
        customer_telephone: [
          { required: true, message: '请输入客户手机号', trigger: 'blur' },
        ],
      },
      // 级联选择器配置项
      options: pca,
      // 工程数据
      engData: [],
      // 分页数据
      params: {
        page: 1,
        pageSize: 5
      },
      // 表单文字宽度
      formLabelWidth: '80px',
      // 总条数
      total: 0,
      // 抽屉标题
      title: "",
      // 控制抽屉隐藏与显示
      dialog: false,
      // 表单对象
      form: {},
    }
  },
  methods: {
    // 跳转到工程详情页面
    toDetails(row) {
      // 路由跳转 并传参
      this.$router.push({
        path: "/am/engineer/Details",
        query: row
      })
    },
    // 去删除未绑定工程
    toDelete(id) {
      this.$confirm('此操作将删除该工程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发送删除请求
        let res = await del('/engineer/deleteById', { id });
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.params.page = 1;
        // 刷新页面 重新请求数据
        this.getEngData();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 模态框关闭清空表单校验
    toClose() {
      this.$refs['myForm'].resetFields();
      this.dialog = false;
    },
    // 去修改
    toEdit(row) {
      // 重置表单校验
      // 弹出抽屉
      this.dialog = true;
      // 修改标题
      this.title = '修改工程信息';
      this.form = { ...row }; //{name,type,}
    },
    // 获取区域经理
    async getCData() {
      let res = await get('/user/pageQuery', {
        page: 1,
        pageSize: 1000,
        role_id: 3
      });
      this.cData = res.data.list;
    },
    // 去录入
    toAdd() {

      // 弹出抽屉
      this.dialog = true;
      // 修改标题
      this.title = '录入工程信息';
      // 清空表单
      this.form = {};
    },
    // 去提交
    toSave() {
      // refs ---->{ name:"zhangsan"} refs['name']
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          // 校验通过
          let obj = { ...this.form };
          obj.address = obj.address1.join('') + obj.address2;
          // 删除不需要 数据 
          delete obj.address1;
          delete obj.address2;
          // 发送保存或者更新请求
          let res = await postJSON('/engineer/saveOrUpdate', obj);
          if (res.status === 200) {
            this.$notify({
              title: '成功',
              message: '保存更新成功!',
              type: 'success'
            });
            // 清空表单校验
            this.toClose();
            // 刷新页面 重新发送请求
            this.getEngData();
          } else {
            this.$notify({
              title: '失败',
              message: '已取消更改!',
              type: 'error'
            });
          }
          // 关闭抽屉
          this.dialog = false;
        } else {
          return false;
        }
      });
    },
    // 获取工程数据
    async getEngData() {
      let res = await get('/engineer/pageQuery', this.params);
      this.engData = res.data.list;
      this.total = res.data.total;
    },
    // 数据条数发生变化函数
    handleSizeChange(pageSize) {
      // console.log(pageSize,'条数');
      // 当条数发生改变 重新请求工程数据
      // params.pageSize --->2 
      this.params.pageSize = pageSize;
      // 重新请求工程数据
      this.getEngData();
    },
    // 页码发生改变函数
    handleCurrentChange(page) {
      // console.log(page,'当前页码');
      this.params.page = page;
      this.getEngData();
    },
    // 去结束
    tofinish(id) {
      this.$confirm("工程结束后将自动解绑设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发送结束工程请求
          let res = await get("/engineer/finish", {
            id: id,
          });
          this.$message({
            type: "success",
            message: "结束成功!",
          });
          // 将页码改为1
          this.params.page = 1;
          // 重新请求工程数据
          this.getEngData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消结束",
          });
        });
    }


  },
  created() {
    this.getEngData();
    this.getCData();
  }
}
</script>